/*global __rolesAndPermissions*/
;(function (win) {
  const { roles, permissions } = __rolesAndPermissions

  /**
   * can('perm1,perm2')
   * @param {String} permsStr
   * @param {Boolean} requireAll default false.
   */
  function can (permsStr, requireAll = false) {
    let requirePerms = permsStr.split(',')
    if (requirePerms.length > 1) {
      if (requireAll) {
        return requirePerms.every(x => can(x))
      } else {
        return requirePerms.some(x => can(x))
      }
    } else {
      for (const perm of permissions) {
        if (perm === permsStr) {
          return true
        }
      }
    }
    return false
  }
  /**
   * hasRole('role1|role2|role3')
   * hasRole('role1')
   * @param {String} roleStr
   */
  function hasRole (roleStr, requireAll = false) {
    let requireRoles = roleStr.split('|')
    if (requireRoles.length > 1) {
      if (requireAll) {
        return requireRoles.every(x => hasRole(x))
      } else {
        return requireRoles.some(x => hasRole(x))
      }
    } else {
      for (const role of roles) {
        if (role === roleStr) {
          return true
        }
      }
    }
    return false
  }
  win.hasRole = hasRole
  win.can = can
})(window)
